<template>
  <div id="loginBox">
    <div class="vBox">
      <video src="@/assets/medium/bgmv.mp4" muted autoplay loop preload="auto" class="bg-video">
      </video>
    </div>
    <el-form :model="loginForm" status-icon :rules="rules" ref="loginForm" label-width="100px" class="login-container">
      <div class="jiaobiao" @click="isErwei=!isErwei">
        <svg class="icon icon-jiao" aria-hidden="true">
          <use :xlink:href="isErwei?'#icon-diannaojiaobiao':'#icon-erweimajiaobiao1'"></use>
        </svg>
      </div>
      <h1>寰球旅游管理系统</h1>
      <!-- 二维码登录 -->
      <div class="erWei" v-if="isErwei">
        <div class="img">
          <img :src="erWeiUrl" alt="" width="200px">
          <i class="mask" v-show="isScancode"></i>
        </div>
        <h3>请使用手机微信扫码登录</h3>
      </div>
      <!-- 普通登录 -->
      <div class="input" v-else>
        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="loginForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-input type="text" class="captcha" v-model="loginForm.captcha" autocomplete="off"
            @keydown.native.enter="submitForm('loginForm')"></el-input>
          <span class="captcha-svg" v-html="captcha" @click="refreshCaptcha()"></span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')">登入</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
<script>
  import {
    loginApi,
    getCaptchaApi,
    verifyCaptchaApi,
    refreshCaptchaApi,
    getScanCodeUrlApi,
    weChatLoginApi
  } from "@/api"
  // 引入socket.io客户端
  import io from "socket.io-client"
  // 引入qrcode
  import qr from "qrcode"
  import deboule from '@/pages/login/deboule'
  import {
    mapState,
    mapMutations
  } from "vuex"
  //1.收集用户的用户名和密码,发送给服务端

  //2.服务端会进行校验,校验通过,返回用户信息和token

  //3.将token存到本地存储

  //4.登入成功需要跳转到主页
  var validateUser = (rule, value, callback) => {
    var uPattern = /^[a-zA-Z0-9_-]{3,16}$/;
    if (uPattern.test(value)) {
      callback()
    } else {
      callback("请输入4-16位(字母、数字、下划线、减号)")
    }
  };
  var validatePss = (rule, value, callback) => {
    if (value == "") {
      return callback("请输入密码")
    } else {
      callback()
    }
  };
  var validateCaptcha = (rule, value, callback) => {
    if (value == "") {
      return callback("验证码输入不能为空")
    } else {
      callback()
    }
  };
  export default {
    created() {
      this.refreshCaptcha()

    },
    data() {
      return {
        isErwei: false, //是否使用二维码登录
        isScancode: false, //是否扫码
        erWeiUrl: "",
        captcha: "",
        loginForm: {
          username: '',
          password: '',
          captcha: "",
        },
        rules: {
          username: [{
            validator: validateUser,
            trigger: 'blur'
          }],
          password: [{
            validator: validatePss,
            trigger: 'blur'
          }],
          captcha: [{
            validator: validateCaptcha,
            trigger: 'blur'
          }],
        }
      };
    },
    methods: {
      ...mapMutations(["SET_USER_BTNS"]),
      refreshCaptcha() {
        deboule(() => {
          getCaptchaApi()
            .then(res => {
              this.captcha = res.data.img
              // console.log(123);
            })
        }, 200)

      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 本地校验通过
            // 解构赋值  
            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            let {
              username,
              password,
              captcha
            } = this.loginForm
            // 验证码验证
            verifyCaptchaApi(captcha)
              .then(res => {
                if (res.data.state) {
                  // 登入成功
                  // 将token保存到本地
                  loginApi(username, password)
                    .then(res => {
                      // console.log(res);
                      if (res.data.state) {
                        // 本地存储 

                        loading.close();
                        localStorage.setItem("hq-token", res.data.token)
                        localStorage.setItem("userInfo", JSON.stringify(res.data.userInfo))
                        // 把用户按钮存放到vuex中
                        localStorage.setItem("userButtons", JSON.stringify(res.data.permission.buttons))
                        this.SET_USER_BTNS(res.data.permission.buttons)
                        this.$router.push({
                          path: "/"
                        })

                      } else {
                        loading.close();
                        this.$message.error("密码或用户名输入错误")
                      }
                    })
                } else {
                  loading.close();
                  this.$message.error("验证码输入错误");
                  this.refreshCaptcha()
                  this.loginForm.captcha = ""
                }
              })
          } else {
            // 本地校验没通过
            return false;
          }
        });
      },
    },
    watch: {
      isErwei(newVal) {
        // 判断用户是否进行二维码登录
        // 如果进行二维码登录，进行scoket.io和服务器进行连接
        if (newVal) { //判断是否使用二维码登录
          // 建立连接
          let socket = io("ws://chst.vip")
          socket.on('connect', () => {
            // console.log("连接成功");
            // 调用接口地址，获得二维码地址
            getScanCodeUrlApi()
              .then(res => {
                // console.log(res);
                let qrUrl = res.data.scanCodeUrl
                // 将二维码地址转化成二维码
                qr.toDataURL(qrUrl, (err, imgUrl) => {
                  if (err) throw err;
                  this.erWeiUrl = imgUrl
                })
              })
          })
          socket.on("scancodeSuccess", (data) => {
            // console.log(data);
            this.isScancode = true;
            let {
              wechatCode
            } = data
            // 微信登录
            weChatLoginApi(wechatCode)
              .then(res => {
                // 1.将token存到本地
                // 2.将用户消息存到本地 
                // 3.跳转主页
                // this.$store.dispatch("GET_MENU_LIST")
                localStorage.setItem("hq-token", res.data.token)
                localStorage.setItem("userInfo", JSON.stringify(res.data.userInfo))
                // 把用户按钮存放到vuex中
                localStorage.setItem("userButtons", JSON.stringify(res.data.permission.buttons))
                this.SET_USER_BTNS(res.data.permission.buttons)
                this.$router.push("/")
              })

          })
        }
      }
    }
  }
</script>


<style scoped lang='less'>
  html,
  body {
    width: 100%;
    height: 100%;
  }

  #logBox {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .vBox {
    width: 100%;
    height: 100%;
    position: fixed;
    overflow: hidden;
    z-index: -11000;
  }

  .bg-video {
    position: absolute;
    top: 50%;
    left: 50%;
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
    z-index: -9999;
    transform: translateX(-50%) translateY(-50%);
    transition: 1s opacity;
    // background-color:skyblue;

  }

  .login-container {
    width: 400px;
    height: 485px;
    position: fixed;
    right: 180px;
    bottom: 120px;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 15px;
    box-sizing: border-box;

    & /deep/.jiaobiao {
      width: 60px;
      height: 60px;

      .icon-jiao {
        width: 60px;
        height: 60px;
        position: absolute;
        right: 3px;
        top: 3px;
        color: white;
      }

    }
  }

  .erWei {
    position: absolute;
    left: 100px;
    top: 180px;

    // 二维码遮罩
    .img {
      display: inline-block;
      position: relative;
      width: 200px;
      height: 200px;

      img {
        position: absolute;
      }

      .mask {
        width: 200px;
        height: 200px;
        background-color: black;
        position: absolute;
        opacity: 0.6;
        background-image: url("../../assets/img/扫码成功.png") !important;
        background-size: 50%;
        background-repeat: no-repeat;
        background-position: center;
      }
    }

    h3 {
      margin-top: 10px;
      color: white;
    }
  }

  .input {
    margin-top: 60px;
    padding-right: 50px;

    .captcha {
      width: 110px;
      vertical-align: top;

      & /deep/ .el-input__inner {
        width: 100%;
        height: 45px;
        border-radius: 5px 0 0 5px;
        border: 0;
        font-size: 18px;
      }

    }

    .el-button {
      margin-left: 20px;
    }

    .captcha-svg {
      background: #fff;
      display: inline-block;
      height: 45px;
      width: 140px;
      text-align: center;
      cursor: pointer;
      border: 0;
      border-radius: 0px 5px 5px 0;
    }

    & /deep/ .el-form-item__label {
      color: white;
    }
  }

  h1 {
    margin-left: 80px;
    margin-top: 30px !important;
    color: white;
  }

  .el-button--primary {
    width: 200px;
  }
</style>